#include "defaults.h"
#include "config.h"

//------------------------------------------------------------------------
Config::Config()
//------------------------------------------------------------------------
{
	// ToDo: Open
}

//------------------------------------------------------------------------
Config::~Config()
//------------------------------------------------------------------------
{
	save();
	delete [] m_path;
}

//------------------------------------------------------------------------
bool Config::open( const TCHAR * path )
//------------------------------------------------------------------------
{
	if( m_path ) { delete [] m_path; }
	m_path = _tcsdup( path );
	FILE * pFile;
	_tfopen_s(&pFile, path, _T("a+"));

	// Configuration file could not be opened.
	if(pFile == NULL) {
		return false;
	}

	// Configuration file was opened.
	fclose(pFile);
	return true;
}

//------------------------------------------------------------------------
bool Config::save()
//------------------------------------------------------------------------
{
	// Default implementation
	return true;
}

//------------------------------------------------------------------------
TCHAR * Config::readString( const TCHAR * name, TCHAR * v )
//------------------------------------------------------------------------
{
	static const int MAX_SIZE = 1024;
	TCHAR * ret = new TCHAR[ MAX_SIZE ];
	ret[MAX_SIZE - 1] = 0;
	GetPrivateProfileStringW( _T("Inplace"), name, v, ret, MAX_SIZE, m_path ); 
	return ret;
}

//------------------------------------------------------------------------
bool Config::readBool( const TCHAR * name, bool v )
//------------------------------------------------------------------------
{
	int ret = readInt( name, ( ( v == true ) ? 1 : 0 ) );
	return ( ret == 1 );
}

//------------------------------------------------------------------------
int Config::readInt( const TCHAR * name, int v )
//------------------------------------------------------------------------
{
	return GetPrivateProfileIntW( _T("Inplace"), name, v, m_path );
}

//------------------------------------------------------------------------
bool Config::writeString( const TCHAR * name, TCHAR * v )
//------------------------------------------------------------------------
{
	return WritePrivateProfileStringW( _T("Inplace"), name, v, m_path );
}

//------------------------------------------------------------------------
bool Config::writeBool( const TCHAR * name, bool v )
//------------------------------------------------------------------------
{
	return writeInt( name, (v) ? 1 : 0 );
}

//------------------------------------------------------------------------
bool Config::writeInt( const TCHAR * name, int v )
//------------------------------------------------------------------------
{
	TCHAR buf[20];
	_itow( v, buf, 10 );
	return WritePrivateProfileStringW( _T("Inplace"), name, buf, m_path );
}